import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/login'
import Layout from '@/views/layout'
import NotFound from '@/views/404'
import Home from '@/views/layout/home'
import Qa from '@/views/layout/qa'
import Video from '@/views/layout/video'
import User from '@/views/layout/user'
import store from '@/store/index'
import Search from '@/views/search'
import SearchResult from '@/views/search/searchResult.vue'
import Article from '@/views/article'
import Edit from '@/views/layout/user/edit'
Vue.use(VueRouter)

const routes = [
  // 这是一级路由
  {
    path: '/',
    component: Layout,
    children: [
      { path: '', component: Home, meta: { isKeeplive: true } },
      { path: 'qa', component: Qa },
      { path: 'video', component: Video },
      { path: 'user', component: User }
    ]
  },
  { path: '/login', component: Login },
  { path: '/search', component: Search },
  { path: '/search/result', component: SearchResult },
  { path: '/article/:id', component: Article },
  { path: '/user/edit', component: Edit },
  { path: '*', component: NotFound }
]

const router = new VueRouter({
  routes
})
// 导航守卫
const urlArr = ['/user', '/user/edit']
router.beforeEach((to, from, next) => {
  const token = store.state.user.token.token
  if (token) {
    next()
  } else {
    if (urlArr.some(item => item === to.path)) {
      // router.push('/login')
      router.push({
        path: '/login',
        query: {
          back: to.fullPath
        }
      })
    }
    next()
  }
  next()
})

export default router
